package com.ftg.learn.spring;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.springframework.util.Assert;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kangjx
 * @createTime 2022/11/29
 */
public class MyClassPathApplicationContext implements MySpringFactory{

    /**
     * 这就是我们自己的容器
     */
    private Map<String,Object> knowBean = new HashMap<>();

    private String path;

    public MyClassPathApplicationContext(String path){
        this.path = path;
        parseXml();
    }

    public void parseXml(){
        SAXBuilder saxBuilder = new SAXBuilder();
        try {
            Document document = saxBuilder.build(new File(path));

            Element root = document.getRootElement();

            // 子节点
            List<Element> beanList = root.getChildren("bean");
            for(Element bean : beanList){
                String idVal = bean.getAttribute("id").getValue();
                String classVal = bean.getAttributeValue("class");

                if(!knowBean.containsKey(idVal)){
                    Class tempClass = Class.forName(classVal);
                    Object temp = tempClass.newInstance();
                    knowBean.put(idVal,temp);
                }else{
                    throw new RuntimeException("对不起，当前id已经存在了");
                }
            }
        } catch (JDOMException | IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    @Override
    public <T> T getBean(Class<T> bean) {
        return findBean(bean);
    }

    private <T> boolean existClass(Class<T> bean){
        Collection cs = this.knowBean.values();
        int num = 0;
        for (Object c : cs) {
            if(c.getClass() == bean){
                num++;
            }
        }
        return num == 1 ? true : false;
    }

    private <T> T findBean(Class<T> bean){
        if(!existClass(bean)){
            throw new RuntimeException(" two 。。。。。。。");
        }
        Collection cs = this.knowBean.values();
        for (Object c : cs) {
            if(c.getClass() == bean){
                return (T) c;
            }
        }
        return null;
    }

    @Override
    public Object getBean(String id) {
        Assert.notNull(id,"请传入你要查找到唯一标识！！");
        return this.knowBean.get(id);
    }
}
